Object Scope and Lifetime

Objects exist only as long as they are referenced. When the class function New is called, it assigns the new object to a variable name. The same object can then be assigned to other variables. For example, this code fragment creates a simple object and then assigns it to a second variable.

X = QUANT.New("SampTime", 1.0, "Sample Time (sec)")

Y = X

... ; other statements

X = 42

In this example, both X and Y initially reference the same object. This object continues to exist and take up space in memory until all references to the object have been reassigned. Thus at the end of the fragment, the object still exists and can be accessed by ifunctions of object Y even though its original variable X has been reassigned.

Once all references to the object have been reassigned, the object is "deleted" and memory used for the object is free to be used by other objects and variables. This may not be important for simple variables such as the QUANT in the example, but can be critical for memory-intensive objects such as data curves.

Often the reassignment that deletes an object occurs naturally in the program flow. Assigning a new value to the variable reassigns the variable. If you want to explicitly delete an object, assign all active references to the object to the data type NIL. In the example above, adding the line

Y = NIL

frees up the memory assigned to the QUANT type object.

The scope and lifetime of objects created and assigned within functions also is crucial. Look at the following function:

function Create&Use()

var1 = CURVE.New("Curve1", ....)

Use(var1)

var2 = 42

return

In this example, var1 is a local variable. It has the value of the CURVE object just created and the data type CURVE. We can refer to this object by its tag, var1. When var1 is passed to function Use(), it is equivalent to sending Curve1 to Use(). When the function Create&Use() is exited at the return statement, var1 disappears and the CURVE object is deleted.

Notice that a function can also return a reference to an object. In this case the returned object is not deleted when the function is exited. See the next example:

X = Create()

 

function Create()

var1 = CURVE.New("Curve1", ....)

... ; other statements

var1

return

Remember, the last expression evaluated is the return value from a function. Because the return value of this function is var1, the CURVE object is not deleted.

Be careful: you can inadvertently return a memory-intensive object from a function, creating unexpected memory-usage problems.

In most cases, you can ignore the question of object lifetime and the related issues of memory-usage. The Explain™ interpreter deletes all objects created by a script when the script's runner window is closed. However, these issues can become critical if you write large scripts with multiple data curves.